package cn.sciento.farm.devicemanager.gateway.uplink.service;

import cn.sciento.farm.devicemanager.common.constant.MqttConstant;
import cn.sciento.farm.devicemanager.common.util.DeviceUtil;
import cn.sciento.farm.devicemanager.gateway.model.uplink.DeviceStatus;
import cn.sciento.farm.devicemanager.gateway.uplink.service.fertilizer.FertilizerDisposeService;
import cn.sciento.farm.devicemanager.gateway.uplink.service.fertilizer.InjectFertilizerDisposeService;
import cn.sciento.farm.devicemanager.gateway.uplink.service.inverter.InverterDisposeService;
import cn.sciento.farm.devicemanager.gateway.uplink.service.sensor.MessageAllDisposeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class SysMessageService {

    @Autowired
    private MessageAllDisposeService messageAllDisposeService;

    @Autowired
    List<InverterDisposeService> inverterDisposeServiceList;

    @Autowired
    private List<FertilizerDisposeService> fertilizerDisposeServiceList;


    @Autowired
    private List<InjectFertilizerDisposeService> injectFertilizerDisposeServiceList;

    public void handle(String topic) {
        String[] subTopic = topic.split("/");
        //判断number符合要求
        if (!DeviceUtil.validateCon(subTopic[4])) {
            return;
        }
        String concentrator = subTopic[4];
//        log.info("上下线消息！！" + "topic:" + topic);
        int status = 0;
        if (subTopic[5].equals(MqttConstant.CONNECTED)) {
            status = 1;
        } else if (subTopic[5].equals(MqttConstant.DISCONNECTED)) {
            status = 0;
        }
        DeviceStatus deviceStatus  = DeviceStatus.builder()
                .eui(concentrator)
                .status(status)
                .build();
        messageAllDisposeService.changeOnline(deviceStatus);
        for(InverterDisposeService disposeService :inverterDisposeServiceList){
            disposeService.changeOnline(concentrator,status);
        }
        for(FertilizerDisposeService disposeService : fertilizerDisposeServiceList){
            disposeService.updateOnline(concentrator,status);
        }

        for(InjectFertilizerDisposeService disposeService : injectFertilizerDisposeServiceList){
            disposeService.handleOnline(concentrator,status);
        }
    }
}
